package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.annotation.Target;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class DishServiceImpl implements DishService {

    private final DishMapper dishMapper;
    private final DishFlavorMapper dishFlavorMapper;
    private final CategoryMapper categoryMapper;
    private final SetmealDishMapper setmealDishMapper;



    @Autowired
    public DishServiceImpl(DishMapper dishMapper, DishFlavorMapper dishFlavorMapper, CategoryMapper categoryMapper, SetmealDishMapper setmealDishMapper){
        this.dishMapper = dishMapper;
        this.dishFlavorMapper = dishFlavorMapper;
        this.categoryMapper = categoryMapper;
        this.setmealDishMapper = setmealDishMapper;
    }

    @Override
    @Transactional
    public void saveWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);

        this.dishMapper.insert(dish);

        Long dishId = dish.getId();

        List<DishFlavor> flavorList = dishDTO.getFlavors();
        if (flavorList != null && !flavorList.isEmpty()){
            flavorList.forEach(dishFlavor -> dishFlavor.setDishId(dishId));
            this.dishFlavorMapper.insertBatch(flavorList);
        }
    }

    @Override
    public DishVO getById(Long id) {
        Dish dish = this.dishMapper.getById(id);
        if (dish == null){ // 如果该ID不存在
            return null;
        }

        List<DishFlavor> flavors = this.dishFlavorMapper.getByDishId(id);
        Category category = this.categoryMapper.getById(dish.getCategoryId());

        DishVO dishVO =  new DishVO();

        BeanUtils.copyProperties(dish, dishVO);
        if (flavors != null && !flavors.isEmpty()){
            dishVO.setFlavors(flavors);
        }
        if (category != null){
            dishVO.setCategoryName(category.getName());
        }
        return dishVO;
    }


    @Override
    public List<Dish> getByCategoryId(Long categoryId) {
        return this.dishMapper.getByCategoryId(categoryId);
    }

    @Override
    public void setStatus(int status, Long id) {
        this.dishMapper.setStatus(status, id);
    }

    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO){
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        try (Page<DishVO> page = this.dishMapper.pageQuery(dishPageQueryDTO)) {
            List<DishVO> dishVOS = page.getResult();
            dishVOS.forEach(dishVO -> {
                Long categoryId = dishVO.getCategoryId();
                Category category = this.categoryMapper.getById(categoryId);
                dishVO.setCategoryName(category.getName());
            });
            return new PageResult(page.getTotal(), dishVOS);
        }
    }

    @Override
    @Transactional
    public void delete(List<Long> ids){
        // 是否含有还在售卖的菜品
        ids.forEach(id -> {
            Dish dish = this.dishMapper.getById(id);
            if (Objects.equals(dish.getStatus(), StatusConstant.ENABLE)){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        });

        // 是否和其他有关联 套餐
        List<Long> setmealIds = this.setmealDishMapper.getSetmealIdsByDishIds(ids);
        if (setmealIds == null || !setmealIds.isEmpty()){
            throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_SETMEAL);
        }

        // 删除菜品
        ids.forEach(id -> {
            this.dishMapper.deleteById(id);
            // 删除关联的口味
            this.dishFlavorMapper.deleteByDishId(id);
        });
    }

    @Override
    @Transactional
    public void update(DishDTO dishDTO){
        Long dishId = dishDTO.getId();
        // 删除原有口味
        this.dishFlavorMapper.deleteByDishId(dishId);

        // 增加新增口味
        List<DishFlavor> dishFlavors = dishDTO.getFlavors();
        if (dishFlavors != null && !dishFlavors.isEmpty()){
            dishFlavors.forEach(dishFlavor -> dishFlavor.setDishId(dishId));
            this.dishFlavorMapper.insertBatch(dishFlavors);
        }

        // 更改当前信息
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        this.dishMapper.update(dish);
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    @Override
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
